package com.zyj.mds.aspect;

import com.zyj.mds.annotation.DataSource;
import com.zyj.mds.config.DataSourceEnum;
import com.zyj.mds.config.DynamicDataSource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Aspect
@Order(1) // @Transactional 的order是 Ordered.LOWEST_PRECEDENCE = Integer.MAX_VALUE ; 其实只要比它小就能包住事务的切面了
@Component
//@EnableTransactionManagement //可以在这里看看事务的顺序
public class DataSourceAspect {

    @Autowired
    private DynamicDataSource dynamicDataSource;

    @Around(value = "@annotation(dataSource)")
    public void proceed(ProceedingJoinPoint joinPoint, DataSource dataSource) throws Throwable {
        DataSourceEnum dataSourceEnum = dataSource.value();
        dynamicDataSource.setDataSourceKey(dataSourceEnum);
        joinPoint.proceed();
        dynamicDataSource.setDataSourceKey(null);
    }
}
